package com.dmgis.qxfw.dataservice.businessservice.picturequiry.controller;

import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.picturequiry.service.PictureQuiryService;
import com.dmgis.qxfw.dataservice.commonservice.common.DbConfig;
import com.dmgis.qxfw.dataservice.commonservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService;
import com.dmgis.qxfw.dataservice.commonservice.utils.DateTime;
import com.dmgis.qxfw.dataservice.commonservice.utils.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.kevinsawicki.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/pictureInfo")
public class PictureQuiryController {
    private  final String operatingSystem;

    @Autowired
    public PictureQuiryController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }

    //MongoService mongoService = new MongoService();
    FileRequestService mongoService = new FileRequestService();
    @Resource
    private PictureQuiryService pictureQuiryService;

    /**
     * 获取图片
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getPicture")
    @ResponseBody
    public Object getPicture(HttpServletRequest request, Model model) throws IOException {

        String type = request.getParameter("type");
        String index = request.getParameter("index");
        DateTime time = new DateTime();
        if (index != null) {
            time = DateTime.now().AddHours(-24).AddHours(Integer.parseInt(index));
        }
        String picpath = "";
        String s = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = s.substring(11, 13);
        if (type.contains("雨量")) {
            String rainType = request.getParameter("rainType");
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Rain\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Rain/";// 临时文件目录
            }

            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            String datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";

            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + rainType + ".png";
            ;
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\Rain\\" + fileName;
                }else {
                    picpath = "Temp/Rain/" + fileName;
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("advCode", DbConfig.advCode);
                map.put("datechar", datechar);
                map.put("type", rainType);
                map.put("collectionName", "sk_rain_png_file");
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);

                    if (operatingSystem.equals("Windows")){
                        picpath = "Temp\\Rain\\" + fileName;
                    }else {
                        picpath = "Temp/Rain/" + fileName;
                    }

                }
            }
        }
        if (type.contains("温度")) {
            String temp = request.getParameter("temp");
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Temp\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Temp/";// 临时文件目录
            }

            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            String datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";

            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + temp + ".png";
            ;
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\Temp\\" + fileName;
                }else {
                    picpath = "Temp/Temp/" + fileName;
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("advCode", DbConfig.advCode);
                map.put("datechar", datechar);
                map.put("type", temp);
                map.put("collectionName", "sk_temp_png_file");
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    if (operatingSystem.equals("Windows")){
                        picpath = "Temp\\Temp\\" + fileName;
                    }else {
                        picpath = "Temp/Temp/" + fileName;
                    }
                }
            }
        }
        if (type.contains("风速")) {
//			String wind = "风速";
            String temp = request.getParameter("temp");
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Wind\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Wind/";// 临时文件目录
            }

            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            String datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";

            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + temp + ".png";
            ;
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\Wind\\" + fileName;
                }else {
                    picpath = "Temp/Wind/" + fileName;
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("advCode", DbConfig.advCode);
                map.put("datechar", datechar);
                map.put("type", temp);
                map.put("collectionName", "sk_wind_png_file");
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);

                    if (operatingSystem.equals("Windows")){
                        picpath = "Temp\\Wind\\" + fileName;
                    }else {
                        picpath = "Temp/Wind/" + fileName;
                    }
                }
            }
        }
        if (type.contains("湿度")) {
//			String humid = "湿度";
            String temp = request.getParameter("temp");
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Humid\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Humid/";// 临时文件目录
            }

            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            String datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";

            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + temp + ".png";
            ;
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\Humid\\" + fileName;
                }else {
                    picpath = "Temp/Humid/" + fileName;
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("advCode", DbConfig.advCode);
                map.put("datechar", datechar);
                map.put("type", temp);
                map.put("collectionName", "sk_humid_png_file");
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    if (operatingSystem.equals("Windows")){
                        picpath = "Temp\\Humid\\" + fileName;
                    }else {
                        picpath = "Temp/Humid/" + fileName;
                    }
                }
            }
        }
        if (type.contains("气压")) {
            String press = "气压";
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Press\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Press/";// 临时文件目录
            }

            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            String datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";

            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + press + ".png";
            ;
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\Press\\" + fileName;
                }else {
                    picpath = "Temp/Press/" + fileName;
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("advCode", DbConfig.advCode);
                map.put("datechar", datechar);
                map.put("type", press);
                map.put("collectionName", "sk_press_png_file");
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    if (operatingSystem.equals("Windows")){
                        picpath = "Temp\\Press\\" + fileName;
                    }else {
                        picpath = "Temp/Press/" + fileName;
                    }
                }
            }
        }

        if (type.equals("雷达图")) {
            // 下载雷达图
            try {
                Map<String, Object> queryMap = JsonUtil.jsonStr2TypeReference(request.getParameter("html"), new TypeReference<Map<String, Object>>() {});
                queryMap.put("elevation",Double.valueOf(queryMap.get("elevation").toString()).toString());
                String fileName = DbConfig.getRadarFileName(
                        queryMap.get("ldtype").toString(),
                        String.valueOf(queryMap.get("elevation")),
                        queryMap.get("stationid").toString(),
                        DateTime.parseDate(queryMap.get("datechar").toString()).toDate(),
                        queryMap.get("timechar").toString()) + ".jpg";
                String urlpath ;
                if (operatingSystem.equals("Windows")){
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\radar\\";// 临时文件目录
                }else {
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/radar/";// 临时文件目录
                }

                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                String servicePath = urlpath + fileName;// 服务器文件
                File serviceFile = new File(servicePath);// 服务器文件
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\radar\\" + fileName;
                }else {
                    picpath = "Temp/radar/" + fileName;
                }

                if (!serviceFile.exists()) {
                    //queryMap.put("advCode",DbConfig.advCode);
                    byte[] data = mongoService.selectData(queryMap);
                    if (new String(data).length() > 0) {
                        FileUtil.bytesToFile(data, servicePath);
                    } else {
                        picpath = "";
                    }
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        if (type.equals("云图")) {
            // 下载雷达图
            try {
                Map<String, Object> queryMap = JsonUtil.jsonStr2TypeReference(request.getParameter("html"), new TypeReference<Map<String, Object>>() {});
                String fileName = DbConfig.getYtFileName(queryMap.get("yttype").toString(),
                        DateTime.parseDate(queryMap.get("datechar").toString()).toDate(),
                        queryMap.get("timechar").toString()) + ".jpg";
                String urlpath ;
                if (operatingSystem.equals("Windows")){
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Cloud\\";// 临时文件目录
                }else {
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Cloud/";// 临时文件目录
                }

                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                String servicePath = urlpath + fileName;// 服务器文件
                File serviceFile = new File(servicePath);// 服务器文件
                if (operatingSystem.equals("Windows")){
                    picpath = "Temp\\Cloud\\" + fileName;
                }else {
                    picpath = "Temp/Cloud/" + fileName;
                }

                if (!serviceFile.exists()) {
//					queryMap.put("advCode",DbConfig.advCode);
                    byte[] data = mongoService.selectData(queryMap);
                    if (new String(data).length() > 0) {
                        FileUtil.bytesToFile(data, servicePath);
                    } else {
                        picpath = "";
                    }
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return picpath.replace('\\', '/');
    }

    /**
     * 获得光图
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getLightPic")
    @ResponseBody
    public Object getLightPic(HttpServletRequest request, Model model) {
        String picpath = "";

        List<base_product> product = pictureQuiryService.getLightPic();
        List<String> temppath = new ArrayList<String>();
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Light\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Light/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        if (product.size() > 0) {
            for (base_product tra : product) {
                String times = new DateTime(tra.getForecasttime()).toDateTimeString();
                String id = tra.getId().toString();
                // 获取文件名称
                String fileName = times.substring(0, 4) + "." + times.substring(5, 7) + "." + times.substring(8, 10)
                        + "." + times.substring(11, 13) + ".png";
                String servicePath = urlpath + fileName;// 服务器文件
                File serviceFile = new File(servicePath);// 服务器文件
                if (serviceFile.exists()) {// 把文件上传到服务器
                    if (operatingSystem.equals("Windows")){
                        picpath = "Temp\\Light\\" + fileName;
                    }else {
                        picpath = "Temp/Light/" + fileName;
                    }

                } else {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("advCode", DbConfig.advCode);
                    map.put("id", id);
                    map.put("table_name", "base_product");
                    map.put("collectionName", "image_file");
                    byte[] data = mongoService.selectData(map);
                    if (data == null) {
                        picpath = "";
                    } else {
                        FileUtil.bytesToFile(data, servicePath);
                        if (operatingSystem.equals("Windows")){
                            picpath = "Temp\\Light\\" + fileName;
                        }else {
                            picpath = "Temp/Light/" + fileName;
                        }

                    }
                }
                if (picpath != null) {
                    File picpathFile = new File(picpath);
                    if (picpathFile.exists()) {
                        return picpath;
                    }
                }
                temppath.add(picpath);
            }
        }
        return temppath;
    }
}
